<?php

namespace siafei\Reporting\ExceptionHandler;

use App\Exceptions\Handler;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Throwable;

class ExceptionHandler extends Handler
{

    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport
        = [
        ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash
        = [
            'password',
            'password_confirmation',
        ];

    /**
     * Report or log an exception.
     *
     * @param \Exception $exception
     *
     * @return void
     * @throws \Exception
     */
    public function report(Throwable $exception)
    {

        if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] == '/favicon.ico') {
            return;
        }
        $this->doThrowableTrace($exception);    //上报消息
        parent::report($exception);
    }


    /**
     * Render an exception into an HTTP response.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Exception $exception
     *
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function render($request, Throwable $exception)
    {
        return parent::render($request, $exception);
    }


    /**
     * 处理
     *
     * @param Throwable $e
     */
    public function doThrowableTrace(Throwable $e)
    {
        $errReport = config('report.err_report');
        if (!$errReport) {
            return;
        }

        $reportExceptions = config('report.report_exception');

        //判断黑名单 是的话 不上报
        if ($this->shouldntReport($e)) {
            return;
        }

        foreach ($reportExceptions as $exceptions) {
            if ($e instanceof $exceptions) {
                app('siafei.report')->report($e); //上报错误信息
                return;
            }
        }
        return;
    }

    /**
     * 判断是否需要上报
     * @param Throwable $e
     * @return bool
     */
    protected function shouldntReport(Throwable $e)
    {
        $dontReport = array_merge(config('report.dosnot_report'), $this->dontReport, $this->internalDontReport);

        return !is_null(Arr::first($dontReport, function ($type) use ($e) {
            return $e instanceof $type;
        }));
    }

}